<template>
  <div class="app-container">
    <el-row class="row bg-white p-l-60">
      <el-form class="ad-form" :model="adForm" :rules="adRules" ref="adForm" label-position="left" label-width="120px">
        <el-form-item class="el-form-item-user"></el-form-item>
        <span class="title">编辑广告位</span>
        <hr>
        <el-form-item class="el-form-item-user"  label="广告链接" prop="link">
          <el-input type="text"  size="small" v-model="adForm.link" placeholder="请输入广告链接"></el-input><br>
          <!--<label v-if="labelShow" class="label">*对公账户需跟主体证件上的机构名称保持一致，对公账户填写指引若个体工商户无对公账户，可填写与营业执照上法人一致的个人银行卡号</label>-->
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="广告类型" prop="ad_type">
          <el-select clearable class="filter-item" size="small" v-model="adForm.ad_type" placeholder="请输入广告类型">
            <el-option v-for="item in adtypeOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="广告版位" prop="position">
          <el-table
            ref="singleTable"
            :data="tableData3"
            highlight-current-row
            @current-change="handleCurrentChange"
            tooltip-effect="dark"
            :header-cell-style="{ borderTop:'1px #f3f3f3 solid'}"
            style="width: 70%">

            <el-table-column
              width="80">
              <template slot-scope="scope">
                <el-input type="hidden" v-model="scope.row.id"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="position_name"
              label="广告版位"
            >
            </el-table-column>
            <el-table-column
              prop="description"
              label="创意形式"
              >
            </el-table-column>
            <el-table-column
              prop="type"
              label="终端类型"
              >
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="广告图" prop="logo">
          <!--<img v-bind:src="dialogImageUrl" v-if="imageShow">-->
          <el-input type="hidden" v-model="adForm.logo"></el-input>
          <el-upload
            class="attach-uploader"
            action=""
            ref="upload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="attach">
            <i v-else class="el-icon-plus attach-uploader-icon"></i>
          </el-upload>
          <div style="width: 80%;display: inline-block">格式要求：支持.jpg .jpeg .bmp .gif .png格式照片，大小不超过5M。</div>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="计划设置" prop="daily_price">
          <el-input placeholder="日限额" @change="handleCalculate" v-model="adForm.daily_price">
            <template slot="prepend">日限额</template>
          </el-input>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="广告位名称" prop="name">
          <el-input type="text"  size="small" v-model="adForm.name" placeholder="广告位名称"></el-input><br>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="用户标签" prop="name">
          <el-checkbox v-model="chk_gender"  label="性别"></el-checkbox>
          <el-checkbox v-model="chk_age" label="年龄"></el-checkbox>
          <el-checkbox v-model="chk_area" label="地域"></el-checkbox>
        <el-checkbox v-model="chk_interest" label="商业兴趣"></el-checkbox>
        </el-form-item>
        <el-form-item v-if="chk_gender || chk_age || chk_area || chk_interest">
          <div class="el-collapse w-50">
            <div v-if="chk_gender" class="el-collapse-item">
              <div class="el-collapse-item__header" :class="{'is-active':switch_gender}">
                <span>性别</span>
                <el-switch
                  class="el-f-r m-t-10"
                  v-model="switch_gender"
                  active-color="#13ce66"
                  inactive-color="#D8D8D8">
                </el-switch>
              </div>
              <div class="el-collapse-item__wrap" :class="{'is-hide':!switch_gender}">
                <div class="el-collapse-item__content" >
                  <el-radio-group v-model="adForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                  </el-radio-group>
                </div>
              </div>
              </div>
              <div v-if="chk_age" class="el-collapse-item">
                <div class="el-collapse-item__header" :class="{'is-active':switch_age}">
                  <span>年龄</span>
                  <el-switch
                    class="el-f-r m-t-10"
                    v-model="switch_age"
                    active-color="#13ce66"
                    inactive-color="#D8D8D8">
                  </el-switch>
                </div>
                <div class="el-collapse-item__wrap" :class="{'is-hide':!switch_age}">
                  <div class="el-collapse-item__content" >
                    <el-select clearable class="filter-item" size="small" v-model="adForm.age_start">
                      <el-option v-for="item in ageOptions" :key="item.key" :label="item.text" :value="item.key">
                      </el-option>
                    </el-select>
                    <el-select clearable class="filter-item" size="small" v-model="adForm.age_end">
                      <el-option v-for="item in ageOptions" :key="item.key" :label="item.text" :value="item.key">
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </div>
              <div v-if="chk_area" class="el-collapse-item">
                <div class="el-collapse-item__header" :class="{'is-active':switch_area}">
                  <span>地域</span>
                  <el-switch
                    class="el-f-r m-t-10"
                    v-model="switch_area"
                    active-color="#13ce66"
                    inactive-color="#D8D8D8">
                  </el-switch>
                </div>
                <div class="el-collapse-item__wrap" :class="{'is-hide':!switch_area}">
                  <div class="el-collapse-item__content" >
                    <el-tree
                      :data="areaTreeData"
                      show-checkbox
                      node-key="id"
                      ref="areaTree"
                      highlight-current
                      :default-checked-keys="area_check"
                      @check-change="handleAreaCheckChange"
                      :props="props">
                    </el-tree>
                  </div>
                </div>
              </div>
              <div v-if="chk_interest" class="el-collapse-item">
                <div class="el-collapse-item__header" :class="{'is-active':switch_interest}">
                  <span>商业兴趣</span>
                  <el-switch
                    class="el-f-r m-t-10"
                    v-model="switch_interest"
                    active-color="#13ce66"
                    inactive-color="#D8D8D8">
                  </el-switch>
                </div>
                <div class="el-collapse-item__wrap" :class="{'is-hide':!switch_interest}">
                  <div class="el-collapse-item__content" >
                    <el-tree
                      :data="tagsTreeData"
                      show-checkbox
                      node-key="id"
                      ref="tagsTree"
                      highlight-current
                      :default-checked-keys="tags_check"
                      @check-change="handleTagscheckChange"
                      :props="props">
                    </el-tree>
                  </div>
                </div>
              </div>
          </div>
        </el-form-item>
        <span class="title">排期与出价</span>
        <hr>
        <el-form-item class="el-form-item-user" label="投放日期" prop="pick_date">
          <el-date-picker
            v-model="adForm.pick_date"
            :editable="false"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="handleDatePickChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="投放时间段">
          <el-radio-group v-model="radio_time" class="redio-fill" fill="#16b8be">
            <el-radio-button label="1">全天</el-radio-button>
            <el-radio-button label="2">特定时间段</el-radio-button>
          </el-radio-group>
          <el-time-select
            placeholder="起始时间"
            v-if="radio_time==2"
            v-model="adForm.time_start"
            :picker-options="{
            start: '00:00',
            step: '00:30',
            end: '23:30'
          }">
          </el-time-select>
          <el-time-select
            placeholder="结束时间"
            v-if="radio_time==2"
            v-model="adForm.time_end"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '23:30',
            }">
          </el-time-select>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="出价方式" prop="pay_type">
          <el-radio-group v-model="adForm.pay_type" @change="handleCalculate" fill="#16b8be">
            <el-radio-button label="1">CPC</el-radio-button>
            <el-radio-button label="2">CPM</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="价格" prop="price">
          <el-input type="text"  size="small" v-model="adForm.price" @change="handleCalculate" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item class="el-form-item-user"  label="预计投放量" prop="daily_count">
          <el-input type="text" readonly size="small"  v-model="adForm.daily_count" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" class="green-btn" :disabled="editDisabled" @click="handleUpdate">修改</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import { validateURL, validateAmount } from '@/utils/validate'
import { uploadFile } from '@/api/uploadFile'
import { getType, getPosition, getDetail, advertisingSave } from '@/api/advertsing'
import { getArea, getTags } from '@/api/assistive'
import { parseTime, in_array } from '@/utils/index'

export default {
  name: 'plan_edit',
  data() {
    const validateAdLink = (rule, value, callback) => {
      if (!validateURL(value)) {
        callback(new Error('请输入正确广告链接'))
      } else {
        callback()
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (!validateAmount(value)) {
        callback(new Error('请输入正确金额'))
      } else {
        callback()
      }
    }
    return {
      queryData: {
        advertsing_id: ''
      },
      adtypeOptions: [],
      adForm: {
        advertsing_id: '',
        link: '',
        ad_type: '',
        logo: '',
        position: '',
        daily_price: '',
        name: '',
        gender: '',
        age_start: '',
        age_end: '',
        pick_date: [],
        start: '',
        end: '',
        time_start: '',
        time_end: '',
        pick_time: '',
        pay_type: '',
        price: '',
        daily_count: '',
        tags: [],
        areas: []
      },
      adRules: {
        link: [{ required: true, trigger: 'blur', validator: validateAdLink },
          { min: 1, max: 120, message: '请输入广告链接（1-120位）', trigger: 'blur' }],
        ad_type: [{ required: true, message: '请选择广告类型', trigger: 'change' }],
        position: [{ required: true, message: '请选择广告版位' }],
        logo: [{ required: true, message: '请上传logo' }],
        daily_price: [{ required: true, trigger: 'blur', validator: validatePrice },
          { min: 1, max: 10, message: '请输入日限额(1-10位)', trigger: 'blur' }],
        name: [{ required: true, message: '请输广告名称', trigger: 'blur' },
          { min: 2, max: 25, message: '请输广告名称(2-25位)', trigger: 'blur' }],
        pick_date: [{ required: true, message: '请选择投放日期' }],
        pay_type: [{ required: true, message: '请选出价方式' }],
        price: [{ required: true, trigger: 'blur', validator: validatePrice },
          { min: 1, max: 5, message: '请输入出价金额(1-5位)', trigger: 'blur' }]
      },
      nextShow: false,
      labelShow: true,
      imageUrl: [],
      imageShow: true,
      loading: false,
      showDialog: false,
      show: true,
      timer: null,
      second: 60,
      ageOptions: [
        { key: 14, text: '14岁' },
        { key: 15, text: '15岁' },
        { key: 16, text: '16岁' },
        { key: 17, text: '17岁' },
        { key: 18, text: '18岁' },
        { key: 19, text: '19岁' },
        { key: 20, text: '20岁' },
        { key: 21, text: '21岁' },
        { key: 22, text: '22岁' },
        { key: 23, text: '23岁' },
        { key: 24, text: '24岁' },
        { key: 25, text: '25岁' },
        { key: 26, text: '26岁' },
        { key: 27, text: '27岁' },
        { key: 28, text: '28岁' },
        { key: 29, text: '29岁' },
        { key: 30, text: '30岁' },
        { key: 31, text: '31岁' },
        { key: 32, text: '32岁' },
        { key: 33, text: '33岁' },
        { key: 34, text: '34岁' },
        { key: 35, text: '35岁' },
        { key: 36, text: '36岁' },
        { key: 37, text: '37岁' },
        { key: 38, text: '38岁' },
        { key: 39, text: '39岁' },
        { key: 40, text: '40岁' },
        { key: 41, text: '41岁' },
        { key: 42, text: '42岁' },
        { key: 43, text: '43岁' },
        { key: 44, text: '44岁' },
        { key: 45, text: '45岁' },
        { key: 46, text: '46岁' },
        { key: 47, text: '47岁' },
        { key: 48, text: '48岁' },
        { key: 49, text: '49岁' },
        { key: 50, text: '50岁' },
        { key: 51, text: '51岁' },
        { key: 52, text: '52岁' },
        { key: 53, text: '53岁' },
        { key: 54, text: '54岁' },
        { key: 55, text: '55岁' },
        { key: 56, text: '56岁' },
        { key: 57, text: '57岁' },
        { key: 58, text: '58岁' },
        { key: 59, text: '59岁' },
        { key: 60, text: '60岁' },
        { key: 61, text: '61岁' },
        { key: 62, text: '62岁' },
        { key: 63, text: '63岁' },
        { key: 64, text: '64岁' },
        { key: 65, text: '65岁' },
        { key: 66, text: '66岁' },
        { key: 67, text: '66岁以上' }
      ],
      tableData3: [],
      dialogImageUrl: '',
      dialogVisible: false,
      chk_gender: false,
      chk_age: false,
      chk_area: false,
      chk_interest: false,
      switch_gender: false,
      switch_age: false,
      switch_area: false,
      switch_interest: false,
      areaTreeData: [],
      area_check: [],
      checkedCity: [],
      tagsTreeData: [],
      tags_check: [],
      checkedTags: [],
      props: {
        children: 'children',
        levle: 'levle',
        label: 'label'
      },
      count: 1,
      radio_date: '',
      radio_time: '',
      is_allDay: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      editDisabled: false
    }
  },
  created() {
    if (this.$route.params.ad_id) {
      this.queryData.advertsing_id = parseInt(this.$route.params.ad_id)
      this.adForm.advertsing_id = parseInt(this.$route.params.ad_id)
    }
    this.getAdType()
    this.getAdPosition()
    this.getAreaTreeData()
    this.getTagsTreeData()
    this.getDetail()
  },
  methods: {
    getDetail() {
      getDetail(this.queryData).then(response => {
        if (response.code === 1) {
          const data = response.data
          this.adForm.link = data.link
          this.adForm.ad_type = data.ad_type
          this.adForm.logo = data.logo
          this.adForm.position = data.position
          this.adForm.daily_price = data.daily_price
          this.adForm.daily_count = data.daily_count
          this.adForm.name = data.name
          this.adForm.gender = data.gender
          this.adForm.age_start = data.age_start
          this.adForm.age_end = data.age_end
          this.adForm.start = data.start
          this.adForm.end = data.end
          this.adForm.time_start = data.time_start
          this.adForm.time_end = data.time_end
          this.adForm.pay_type = data.pay_type
          this.adForm.price = data.price
          this.adForm.link = data.link
          for (const v of this.tableData3) {
            if (v.id === data.position) {
              const index = this.tableData3.indexOf(v)
              this.$refs.singleTable.setCurrentRow(this.tableData3[index])
              break
            }
          }
          if (data.gender !== 3 && data.gender > 0) {
            this.chk_gender = true
            this.switch_gender = true
          }
          if (data.age_start > 0 && data.age_end > 0) {
            this.chk_age = true
            this.switch_age = true
          }
          if (data.area && (data.area instanceof Array) && data.area.length > 0) {
            this.switch_area = true
            this.chk_area = true
            this.adForm.areas = data.area
            for (const v of data.area) {
              this.area_check.push(v.id)
            }
          }
          if (data.tags && (data.tags instanceof Array) && data.tags.length > 0) {
            this.chk_interest = true
            this.switch_interest = true
            this.adForm.tags = data.tags
            for (const v of data.tags) {
              this.tags_check.push(v.id)
            }
          }

          if (data.time_start && data.time_end) {
            this.radio_time = 2
          } else {
            this.radio_time = 1
          }
          const end = new Date(data.end)
          const start = new Date(data.start)

          this.adForm.pick_date = [start, end]
          this.imageUrl = data.logo_imge
        }
      })
    },
    getAdType() {
      getType().then(response => {
        if (response.code === 1) {
          this.adtypeOptions = response.data
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        }
      })
    },
    getAdPosition() {
      getPosition().then(response => {
        if (response.code === 1) {
          this.tableData3 = response.data
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        }
      })
    },
    getAreaTreeData() {
      getArea().then(response => {
        if (response.code === 1) {
          this.areaTreeData = response.data
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        }
      })
    },
    getTagsTreeData() {
      getTags().then(response => {
        if (response.code === 1) {
          this.tagsTreeData = response.data
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        }
      })
    },
    beforeUpload(file) {
      const acceptImage = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = in_array(file.type, acceptImage)
      const islt5M = file.size / 1024 / 1024 < 5
      if (!islt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      if (!isImage) {
        this.$message.error('上传文件格式不对!')
      }
      return isImage && islt5M
    },
    handleUpload(file) {
      const self = this
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.onloadend = function() {
        const data = {}
        data.imgBase64 = this.result
        data.img_type = 'ad_logo'
        uploadFile(data).then(response => {
          if (response.code === 1) {
            self.adForm.logo = response.data.attach_id
            self.imageUrl = response.data.imageUrl
          } else {
            self.$message.error('文件上传失败')
          }
        })
      }
      this.fileList = []
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {

    },
    handleCurrentChange(val) {
      this.currentRow = val
      this.adForm.position = val.id
    },
    handleAreaCheckChange(data, checked, indeterminate) {
      this.adForm.areas = this.$refs.areaTree.getCheckedNodes()
    },
    handleTagscheckChange(data, checked, indeterminate) {
      this.adForm.tags = this.$refs.tagsTree.getCheckedNodes()
    },
    handleDatePickChange() {
      this.adForm.start = parseTime(new Date(this.adForm.pick_date[0]), '{y}-{m}-{d}')
      this.adForm.end = parseTime(new Date(this.adForm.pick_date[1]), '{y}-{m}-{d}')
    },
    handleCalculate() {
      if (this.adForm.daily_price && this.adForm.price && this.adForm.pay_type) {
        if (this.adForm.pay_type === '1') { /* CPC */
          const daily_tmp_price = parseFloat(this.adForm.daily_price)
          const tmp_price = parseFloat(this.adForm.price)
          this.adForm.daily_count = Math.floor(daily_tmp_price / tmp_price)
        } else { /* cmp */
          const daily_tmp_price = parseFloat(this.adForm.daily_price)
          const tmp_price = parseFloat(this.adForm.price)
          this.adForm.daily_count = Math.floor(daily_tmp_price / tmp_price * 1000)
        }
      }
    },
    handleUpdate() {
      this.editDisabled = true
      this.$refs.adForm.validate(valid => {
        if (valid) {
          advertisingSave(this.adForm).then(response => {
            if (response.code === 1) {
              this.$message({
                title: '成功',
                message: '修改成功！',
                type: 'success',
                duration: 3000
              })
              setTimeout(() => {
                window.location.reload()
              }, 3 * 1000)
            } else {
              setTimeout(() => {
                this.$message.error(response.data.msg)
              }, 3 * 1000)
            }
          })
        } else {
          this.labelShow = false
        }
      })
    }
  }
}
</script>


<style rel="stylesheet/scss" lang="scss">

  .el-input {
    width: 70%;
  }
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    color: #fff;
    background-color: #16b8be;
    border-color: #16b8be;
    -webkit-box-shadow: -1px 0 0 0 #16b8be;
    box-shadow: -1px 0 0 0 #16b8be;
  }
  .el-radio-button__inner:hover {
    color: #16b8be;
  }
  .current-row>td{
    background: #16b8bd !important;
    color: #fff;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .attach-uploader{
    /*border: 1px solid #d9d9d9;*/
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    /*overflow: hidden;*/
  }
  .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
  }
  .attach-uploader{
    width: 178px;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .attach-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid #d9d9d9;
  }
  .attach {
    display: block;
  }
</style>
